/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package battleroom;

import com.jme3.bounding.BoundingBox;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Spatial;
import java.util.ArrayList;

/**
 *
 * @author Adam
 */
public class Utility {
    private final Main app;
    ArrayList<Spatial> outlines;
    Material matOutline;
    
    public Utility(Main app)
    {
        this.app = app;       
        outlines = new ArrayList<Spatial>();
    }
    
    public void outlineSpatial(Spatial toOutline, float outlineSize, ColorRGBA color)
    {        
        Spatial outline = toOutline.clone();
        if(outlines.contains(outline)) return;        
        
        Vector3f extent = ((BoundingBox) toOutline.getWorldBound()).getExtent(new Vector3f());   
        
        matOutline = new Material(app.getAssetManager(), "MatDefs/outlineDef.j3md");
        matOutline.setColor("Color", color);
        matOutline.setFloat("Size", outlineSize);
        
        outline.setMaterial(matOutline);
        outline.setName("outline");
        outline.setUserData("size", outlineSize);
        outline.setUserData("origin", toOutline.getLocalTranslation());        
        outline.setUserData("spatSize", extent.getX()*2);
        outline.setQueueBucket(Bucket.Transparent);
        toOutline.getParent().attachChild(outline);
        outlines.add(outline);
    }
    
    public void destroyOutline(Spatial toDestroy)
    {
        Spatial outline = toDestroy.getParent().getChild("outline");
        if(outline == null) return;
        
        outlines.remove(outline);
        toDestroy.getParent().detachChild(outline);        
    }
    
    private Vector3f calculatePlayerOffsetDir(Vector3f vec)
    {
        return vec.subtract(app.getPlayer().getRootNode().getLocalTranslation());
    }
    
    public void update(float tpf)
    {
        if(outlines.size() > 0)
        {
            for(Spatial outline : outlines)
            {
                Vector3f origin = (Vector3f)outline.getUserData("origin");
                Vector3f distance = origin.subtract(app.getPlayer().getRootNode().getLocalTranslation());
                Vector3f offset = distance.normalize(); 
                matOutline.setVector3("offset", distance);
                float spatSize = (Float)outline.getUserData("spatSize");
                float size = (Float)outline.getUserData("size");
                offset.multLocal(
                                      spatSize+(4*size)
                        );
                System.out.println(offset);
                outline.setLocalTranslation(origin.add(offset));
            }
        }
    }
    
}
